package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.constant.AccountType;
import com.qiche.dto.AgentDto;
import com.qiche.dto.BatchToMerchantDto;
import com.qiche.dto.VoucherPackageDto;
import com.qiche.model.*;
import com.qiche.service.*;
import com.qiche.util.PasswordHelper;
import com.qiche.util.UserUtils;
import com.qiche.vo.BatchPostCardVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理商卡包管理控制器
 * Created by Linzw on 2018/01/24.
 */
@Api(value = "/voucherPackages", description = "代理商卡包管理控制器")
@RestController
@RequestMapping("/voucherPackages")
public class VoucherPackageController {
    @Autowired
    private VoucherPackageService packageService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private VoucherRepositoryService repositoryService;

    @ApiOperation(value = "根据条件和分页获取门店列表")
    @GetMapping
    public Map<String, Object> getAll(VoucherPackage pack, @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) throws Exception {
        Map<String, Object> map = new HashMap<>();
        User currentUser =UserUtils.getCurrentUser();
        Agent agent =agentService.selectByAccountId(currentUser.getId());
        if(agent== null){
            return null;
        }
        pack.setAgentId(agent.getId());
        PageInfo<VoucherPackage> pageInfo = packageService.selectByPage(pack, page, limit);

        List<VoucherPackageDto> dtoList=new ArrayList<>();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        pageInfo.getList().forEach(voucherPackage -> {
            VoucherPackageDto dto=new VoucherPackageDto();
            dto.setId(voucherPackage.getId());
            dto.setAmount(voucherPackage.getAmount());
            dto.setName(voucherPackage.getName());
            dto.setQuantity(voucherPackage.getQuantity());
            dto.setCreateTime(voucherPackage.getCreateTime());
            if(voucherPackage.getIndefinite()==1){
                dto.setDueTime("长期有效");
            }else if(voucherPackage.getIndefinite()==0){
                dto.setDueTime(simpleDateFormat.format(voucherPackage.getDueTime()));
            }
            dtoList.add(dto);
        });
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", dtoList);
        return map;
    }


    @ApiOperation(value = "添加代金券包")
    @Transactional
    @PostMapping
    public Result add(@RequestBody @Valid VoucherPackage voucherPackage, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        User currentUser = UserUtils.getCurrentUser();
        Agent agent = agentService.selectByAccountId(currentUser.getId());
        if (agent == null) {
            return Result.createByErrorMessage("不支持的操作");
        }
        voucherPackage.setAgentId(agent.getId());
        int saveCount = packageService.save(voucherPackage);
        if (saveCount > 0) {
            return Result.createBySuccessMessage("添加成功");
        }
        return Result.createByErrorMessage("添加失败");
    }

    @ApiOperation(value = "更新代金券包")
    @Transactional
    @PutMapping
    public Result update(@RequestBody @Valid VoucherPackage voucherPackage, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        User currentUser = UserUtils.getCurrentUser();
        Agent agent = agentService.selectByAccountId(currentUser.getId());
        if (agent == null) {
            return Result.createByErrorMessage("不支持的操作");
        }
        int updateCount = packageService.updateNotNull(voucherPackage);
        if (updateCount > 0) {
            return Result.createBySuccessMessage("更新成功");
        }
        return Result.createByErrorMessage("更新失败");
    }


    @ApiOperation(value = "根据ID删除代金券包")
    @DeleteMapping(value = "/delete/{id}")
    @Transactional
    public Result delete(@PathVariable("id") Long packId) {
        User currentUser = UserUtils.getCurrentUser();
        Agent agent = agentService.selectByAccountId(currentUser.getId());
        if (agent == null) {
            return Result.createByErrorMessage("不支持的操作");
        }
        int deleteCount = packageService.delete(packId);
        if (deleteCount > 0) {
            return Result.createBySuccessMessage("删除成功");
        }
        return Result.createByErrorMessage("删除失败");
    }


    @ApiOperation(value = "根据ID获取代金券包信息")
    @GetMapping(value = "/getById/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        VoucherPackage voucherPackage = packageService.selectByKey(id);
        if (voucherPackage == null) {
            return Result.createByErrorMessage("不存在的代金券包");
        }
        return Result.createBySuccess(voucherPackage);
    }

    @ApiOperation(value = "根据选中的门店列表批量发券")
    @PostMapping(value = "/batchSend")
    public Result batchSend(@RequestBody BatchToMerchantDto batchToMerchantDto) {
        Long masterId = batchToMerchantDto.getMasterId();
        VoucherPackage voucherPackage = packageService.selectByKey(masterId);
        List<Integer> merchantIdList = batchToMerchantDto.getMerchantIdList();
        if (merchantIdList.isEmpty()) {
            return Result.createByErrorMessage("找不到需要发送的门店");
        }
        boolean isOk = true;
        for (Integer merchantId : merchantIdList) {
            Merchant merchant = merchantService.selectByKey(merchantId);
            if (merchant != null) {
                VoucherRepository voucherRepository = new VoucherRepository();
                voucherRepository.setAgentId(voucherPackage.getAgentId());
                voucherRepository.setAmount(voucherPackage.getAmount());
                voucherRepository.setIndefinite(voucherPackage.getIndefinite());
                voucherRepository.setDueTime(voucherPackage.getDueTime());
                voucherRepository.setName(voucherPackage.getName());
                voucherRepository.setQuantity(voucherPackage.getQuantity());
                voucherRepository.setMerchantId(merchantId);
                isOk = repositoryService.save(voucherRepository) > 0 && isOk;
            }
        }
        if (isOk) {
            return Result.createBySuccessMessage("批量发券成功");
        }
        return Result.createByErrorMessage("批量发券失败");
    }

}
